#include <butil/logging.h>
#include<brpc/channel.h>
#include<memory>
#include<iostream>
#include <thread>

#include "main.pb.h"
#include "../../common/etcd.hpp"
#include "../../common/channel.hpp"

int main()
{
    InitLog(false);

    //1.创建信道管理
    xu::ServiceManage::ptr service_manage = std::make_shared<xu::ServiceManage>();
    service_manage->AddFollow("/service/echo");

    //2.创建发现客户端
    auto put = std::bind(&xu::ServiceManage::onServiceOnline,service_manage.get(),std::placeholders::_1,std::placeholders::_2);
    auto del = std::bind(&xu::ServiceManage::onServiceOffline,service_manage.get(),std::placeholders::_1,std::placeholders::_2);
    xu::Discovery::ptr dis = std::make_shared<xu::Discovery>("http://127.0.0.1:2379","/service",put,del);

    //3.获取信道，调用服务
    while(1)
    {
        xu::ServiceChannel::ChannelPtr channel = service_manage->Choose("/service/echo");
        if(channel == nullptr)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
        }
        demo::EchoService_Stub stub(channel.get());
        demo::EchoRequest req;
        req.set_msg("你好，徐");
        auto rsp = new demo::EchoResponse();
        brpc::Controller *cntl = new brpc::Controller();;
        stub.Echo(cntl,&req,rsp,nullptr);
        if(!cntl->Failed())
        {
            std::cout<<rsp->msg()<<std::endl;
        }

    }
    
    std::this_thread::sleep_for(std::chrono::seconds(10));
    return 0;
}